package com.darrenchan.leetcode;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2019-11-27 00:14
 */
public class Q14 {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0){
            return "";
        }
        String pre = strs[0];
        for (int i = 1; i < strs.length; i++) {
            pre = commonPre(pre, strs[i]);
        }
        return pre;
    }

    private String commonPre(String pre, String str) {
        StringBuilder sb = new StringBuilder();
        int index1 = 0, index2 = 0;
        while(index1 < pre.length() && index2 < str.length()){
            if(pre.charAt(index1) == str.charAt(index2)){
                sb.append(pre.charAt(index1));
                index1++;
                index2++;
            }else{
                break;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Q14().longestCommonPrefix(new String[]{"dog","racecar","car"}));
    }
}
